package com.run_java_test.t.test_code;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

@RestController
public class AdminController {

    @Autowired
    private GenericWebApplicationContext context;

    @Autowired
    private GenericWebApplicationContext genericWebApplicationContext;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @GetMapping("/loadController")
    public String loadController() {
        try {
            // 1. 编译 Java 文件
            DynamicJavaCompiler.compileJavaFile("E:\\test\\com\\run_java_test\\test_code\\DynamicController.java");

            // 2. 加载编译后的类
            Class<?> controllerClass = DynamicClassLoader.loadClass("E:\\test\\", "com.run_java_test.test_code.DynamicController");

            // 3. 注册控制器
            ControllerLoader.registerController(controllerClass, context, requestMappingHandlerMapping);

            return "Controller loaded and registered!";
        } catch (Exception e) {
            System.out.println(e);
            return "Error loading controller: " + e.getMessage();
        }
    }

    // 卸载控制器
    @GetMapping("/unloadController")
    public String unloadController() {
        // 移除动态注册的控制器 Bean
        ControllerLoader.unloadController("DynamicController", context);
        return "Controller unloaded!";
    }

    @Autowired
    private ApplicationContext applicationContext;


    @Autowired
    private ControllerMappingChecker controllerMappingChecker;

    @GetMapping("/checkDynamicController")
    public String checkDynamicController() {
        controllerMappingChecker.checkControllerMappings();
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        for (String beanName : beanNames) {
            if (beanName.contains("DynamicController")) {
                return "DynamicController is registered as bean: " + beanName;
            }
        }
        return "DynamicController is NOT registered!";
    }
}
